package loadsave.loadsaveobject;

import java.util.*;

import loadsave.Saver;

public class LoadSaveMapComposite extends LoadSaveComposite {
	private Map<LoadSaveObject, LoadSaveObject> values;
	private String keyType, valType;
	
	public LoadSaveMapComposite(String name, String type, String keyType, String valType) {
		super(name, type);
		this.keyType = keyType;
		this.valType = valType;
		values = new HashMap<LoadSaveObject, LoadSaveObject>();
	}
	
	@Override
	public Iterator<LoadSaveObject> getIterator() {
		return new Iterator<LoadSaveObject>() {
			java.util.Iterator<LoadSaveObject> iter;
			LoadSaveObject currKey, currVal;
			boolean nextExists = true;
			 
			@Override
			public void init() {
				iter = values.keySet().iterator();
				next();
			}

			@Override
			public boolean hasNext() {
				return nextExists;
			}

			@Override
			public void next() {
				if (iter.hasNext()) {
					currKey = iter.next();
					currVal = values.get(currKey);
				}
				else
					nextExists = false;
			}

			@Override
			public LoadSaveObject getCurrKey() {
				return currKey;
			}

			@Override
			public LoadSaveObject getCurrVal() {
				return currVal;
			}
			
		};
	}

	public String getKeyType() {
		return keyType;
	}
	
	public String getValType() {
		return valType;
	}
	
	public void add(LoadSaveObject key, LoadSaveObject value) {
		values.put(key, value);
	}

	@Override
	public void save(Saver s) {
		s.saveLoadSaveMapComposite(this);
	}
	
	@Override
	/**
	 * Returns a string representation of this LoadSaveMapComposite object. Solely for testing purposes.
	 */
	public String toString() {
		StringBuilder toReturn = new StringBuilder();
		toReturn.append("LoadSaveMapComposite: ");
		toReturn.append(getName());
		toReturn.append(':');
		toReturn.append(getType());
		toReturn.append('<');
		toReturn.append(getKeyType());
		toReturn.append(',');
		toReturn.append(getValType());
		toReturn.append("> = [\n");
		Iterator<LoadSaveObject> i = getIterator();
		for (i.init(); i.hasNext(); i.next()) {
			String s = i.getCurrKey().toString();
			toReturn.append(s.substring(0, s.length() - 1));
			toReturn.append(", ");
			toReturn.append(i.getCurrVal().toString());
		}
		toReturn.append("]\n");
		return toReturn.toString();
	}

}
